from django.http import JsonResponse
from django.db import transaction
from django.conf import settings
from .models import Text,Tag,Tagging
from django.contrib.auth import get_user_model
import requests
import json
import logging
import re

#修改API返回格式

logger=logging.getLogger(__name__ )
User = get_user_model()


NVIDIA_API_ENDPOINT = "https://integrate.api.nvidia.com/v1/chat/completions"
MODEL_NAME = "deepseek-ai/deepseek-r1"
# API_KEY = "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"
API_KEY = "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"
HEADERS = {
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json"
}


def api_generate_tags(request):
    if request.method == 'POST':
        try:
            data = json.loads(request.body)
            input_text = data.get('text', '')[:2048]

            if not input_text.strip():
                return JsonResponse({'status': 'error', 'message': '输入内容不能为空'}, status=400)

            # 获取当前用户（如果已认证）
            user = request.user if request.user.is_authenticated else None

            with transaction.atomic():
                # 检查文本是否已存在
                if Text.objects.filter(content=input_text).exists():
                    return JsonResponse({
                        'status': 'error',
                        'message': '该文本内容已存在，不能重复提交',
                        'existing': True
                    }, status=409)

                # 1. 创建文本记录
                text_obj = Text.objects.create(content=input_text)

                # 2. 生成标签
                tags = get_tags_with_nvidia(input_text)

                # 3. 处理标签关联
                created_tags = []
                for tag_name in tags:
                    # 创建或获取标签（名称唯一）
                    tag, created = Tag.objects.get_or_create(
                        name=tag_name,
                        defaults={'creator': user}
                    )

                    # 创建关联记录
                    Tagging.objects.create(
                        tag=tag,
                        text=text_obj,
                        user=user
                    )

                    created_tags.append(tag.name)

                return JsonResponse({
                    'status': 'success',
                    'tags': created_tags,
                    'text_id': text_obj.id
                })

            # tags = get_tags_with_nvidia(input_text)
            # return JsonResponse({'status': 'success', 'tags': tags})

        except json.JSONDecodeError:
            return JsonResponse({'status': 'error', 'message': '非法JSON格式'}, status=400)
        except Exception as e:
            logging.error(f"[API Error] 详细错误: {str(e)}", exc_info=True)  # 记录完整堆栈
            return JsonResponse({'status': 'error', 'message': '内部服务器错误'}, status=500)


def get_tags_with_nvidia(text):
    """调用API生成标签"""
    try:
        payload = {
            "model": settings.NVIDIA_MODEL_NAME,
            "messages": [{
                "role": "user",
                "content": f'''请严格遵循以下要求:
                              1. 分析下方文本内容
                              2. 生成最多5个最相关的主题标签
                              3. 直接输出用英文逗号分隔的标签，不要编号、不要解释
                              4. 每个标签使用#开头，格式示例：#量子计算,#计算机科学
                              5. 每个标签为2-4个字的短语，示例格式：春日清晨,自然之美
                              文本内容：{text}'''
            }],
            "temperature": 0.3,
            "max_tokens": 2048
        }

        response = requests.post(
            NVIDIA_API_ENDPOINT,
            headers=HEADERS,
            # headers={
            #     "Authorization": f"Bearer {settings.NVIDIA_API_KEY}",
            #     "Content-Type": "application/json"
            # },
            json=payload,
            timeout=2048
        )

        response.raise_for_status()
        return parse_response(response.json())

    except requests.exceptions.HTTPError as exc:
        logger.error(
            "NVIDIA API请求失败 HTTP %s: %s",
            exc.response.status_code,
            exc.response.text,
            exc_info=True
        )
    except requests.exceptions.RequestException as exc:
        logger.error("NVIDIA API请求异常: %s", str(exc), exc_info=True)
    except Exception as exc:
        logger.error("未处理的异常: %s", str(exc), exc_info=True)

    return []


def parse_response(response_data):
    """解析API响应"""
    try:
        content = response_data["choices"][0]["message"]["content"]
        clean_text = re.sub(r'<think>.*?</think>', '', content, flags=re.DOTALL).strip()
        # clean_text = clean_text.strip()
        tags = [tag.strip("#, ") for tag in clean_text.split(",") if tag.strip()]
        # return list({tag: None for tag in tags}.keys())[:5]
        seen = set()
        return [tag for tag in tags if not (tag in seen or seen.add(tag))][:5]
    except KeyError as exc:
        logger.error("API响应缺少关键字段: %s", str(exc), exc_info=True)
    except Exception as exc:
        logger.error("解析响应时发生异常: %s", str(exc), exc_info=True)

    return []



